/**
 * Created by Administrator on 2015/9/1.
 */
var userDao = require('../dao/userDao');
var userInfoDao = require('../dao/userInfoDao');
var activeDao = require('../dao/activeDao');

module.exports = {
    add: function (req, res, callback) {
        userDao.add(req, res, function (result) {
            callback(result)
        });
    },
    login: function (req, res, callback) {
        userDao.login(req, res, function (result) {
            if (result.length > 0) {
                userInfoDao.queryById(req,res, result[0], function (userInfoResult,req,res) {
                    var user = {
                        id: result[0].id,
                        username: result[0].username,
                        password: result[0].password,
                        level: result[0].level,
                        regisTime: result[0].regisTime,
                        userInfoId: result[0].userInfoId,
                        address: userInfoResult[0].address,
                        birthday: userInfoResult[0].birthday,
                        email: userInfoResult[0].email,
                        name: userInfoResult[0].name,
                        sex: userInfoResult[0].sex,
                        tel: userInfoResult[0].tel,
                    }
                    req.session.currentUser = user;
                    if (req.param('isRemember') == 'on') {
                        res.cookie['localUsername'] = user.username;
                    } else {
                        res.cookie['localUsername'] = undefined;
                    }
                    callback(user,req);
                })
            } else
                callback(undefined);
        });
    },
    checkUsername: function (req, res, callback) {
        userDao.checkUsername(req, res, function (result) {
            if (result.length == 0) {
                result = "success";
            } else {
                result = "failure";
            }
            callback(result);
        });
    },
    register: function (req, res, callback) {
        userInfoDao.add(req, res, function (userInfoId) {
            userInfoId = userInfoId.content.insertId;
            userDao.register(req, res, userInfoId, function (result) {
                if (result.affectedRows >= 0) {
                    result = "success";
                } else {
                    result = "failure";
                }
                callback(result);
            });
        })

    },
    firstPages: function (req, res, callback) {
        activeDao.queryNews(req,function (result) {
            callback(result)
        });
    },

}